package com.demo.http.androidnative;

import com.demo.http.HttpCallback;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by yangming on 16-11-15.
 */
public class HttpURLConnectionUtil {

    protected final int SOCKET_TIMEOUT = 10000;

    protected final String GET = "GET";

    protected final String POST = "POST";

    private HttpCallback mCallback = null;

    public void setCallback(HttpCallback callback) {
        this.mCallback = callback;
    }

    public void get(String host, Map<String, String> params) {
        byte[] bytes;
        try {
            StringBuilder stringBuilder = new StringBuilder(host);
            if (null != params && !params.isEmpty()) {
                stringBuilder.append("?");
                Iterator it = params.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry element = (Map.Entry) it.next();
                    stringBuilder.append(element.getKey());
                    stringBuilder.append("=");
                    stringBuilder.append(element.getValue());
                    stringBuilder.append("&");
                }
            }
            String requestString = stringBuilder.toString();
            URL uri = new URL(requestString);
            HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
            conn.setConnectTimeout(SOCKET_TIMEOUT);
            conn.setRequestMethod(GET);
            int statusCode = conn.getResponseCode();
            if (statusCode != HttpURLConnection.HTTP_OK) {
                if (null != mCallback) {
                    mCallback.onFailure(statusCode, null);
                }
                return;
            }

            InputStream inputStream = conn.getInputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream);
            byte[] buffer = new byte[1024 * 8];
            int length;
            while (0 < (length = bufferedInputStream.read(buffer))) {
                bufferedOutputStream.write(buffer, 0, length);
            }
            bufferedOutputStream.flush();
            bytes = byteArrayOutputStream.toByteArray();
            if (null != mCallback) {
                mCallback.onResponse(bytes);
            }
            inputStream.close();
            bufferedOutputStream.close();
            bufferedInputStream.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            if (null != mCallback) {
                mCallback.onFailure(0, e);
            }
        }
    }

    public void post(String host, Map<String, String> params) {
        byte[] bytes;
        try {
            StringBuilder stringBuilder = new StringBuilder();
            Iterator it = params.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry element = (Map.Entry) it.next();
                stringBuilder.append(element.getKey());
                stringBuilder.append("=");
                stringBuilder.append(element.getValue());
                stringBuilder.append("&");
            }
            String requestString = stringBuilder.toString();
            URL uri = new URL(host);
            HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
            conn.setConnectTimeout(SOCKET_TIMEOUT);
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(requestString.getBytes().length));
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod(POST);
            OutputStream outputStream = conn.getOutputStream();
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream));
            writer.write(requestString);
            writer.flush();
            int statusCode = conn.getResponseCode();
            if (statusCode != HttpURLConnection.HTTP_OK) {
                if (null != mCallback) {
                    mCallback.onFailure(statusCode, null);
                }
                return;
            }

            InputStream inputStream = conn.getInputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream);
            byte[] buffer = new byte[1024 * 8];
            int length;
            while (0 < (length = bufferedInputStream.read(buffer))) {
                bufferedOutputStream.write(buffer, 0, length);
            }
            bufferedOutputStream.flush();
            bytes = byteArrayOutputStream.toByteArray();
            if (null != mCallback) {
                mCallback.onResponse(bytes);
            }
            outputStream.close();
            writer.close();
            inputStream.close();
            bufferedOutputStream.close();
            bufferedInputStream.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            if (null != mCallback) {
                mCallback.onFailure(0, e);
            }
        }
    }
}
